import MSData
import WorkerMSAPI
import WorkerMSDB
import MSLogger
import MSDBTemplates

import time
import datetime
import os
import sys
import heartbeating
import pdb

MSLogger.logInit('C:\\safe\\ms.cleaner.log', 6, True)
MSLogger.logInfo('ms cleaner started')
reader = WorkerMSDB.Worker('localhost', '2929', 'PGSMData', 'sa', 'safeinside')
reader.connect()

if os.path.exists('c:\\safe\\ms.cleaner.pid'):
    MSLogger.logError('ms autotester already running')
    sys.exit()

f = open('c:\\safe\\ms.cleaner.pid', 'w')
f.close()

cursor = reader.connection.cursor()

query = 'SELECT TOP(1) id, eventTime FROM _event_data_internal'
cursor.execute(query)
res   = cursor.fetchall()
if len(res) == 0:
    MSLogger.logInfo('table _event_data_internal is empty - exit now')
    sys.exit()
first = res[0][1]
lowerbound  = datetime.datetime(year=first.year, month=first.month, day=first.day)
delta       = datetime.timedelta(days=1)

try:
    while True:
        lowerbound += delta
        MSLogger.logInfo('cleaning till %s' % (str(lowerbound)))
        query = 'DELETE FROM _event_data_internal WHERE eventTime<%s' % (lowerbound.strftime(MSData.TIME_FORMAT_MAGICDB))
        cursor.execute(query)
        time.sleep(20)
        cursor.commit()
        if datetime.datetime.fromtimestamp(time.time()) - lowerbound > datetime.timedelta(days=365):
            continue
        MSLogger.logInfo('all cleaned')
        break
except KeyboardInterrupt:
    MSLogger.logError('ms cleaner stopped')
except Exception, err:
    MSLogger.logError('ms cleaner fatal error: %s' % (str(err)))
finally:
    os.unlink('c:\\safe\\ms.autotester.pid')
